import { getAccountPage } from '@/services/api/api-admin-account';
import { treeOrganization } from '@/services/api/api-admin-organization';
import { previewOrganizationStatistics } from '@/services/api/api-user-analysis';

import { FolderOutlined } from '@ant-design/icons';
import ProCard from '@ant-design/pro-card';
import ProTable, { ActionType, ProColumns } from '@ant-design/pro-table';
import { Space, Tag, Tree } from 'antd';
import { DataNode } from 'antd/lib/tree';
import RcResizeObserver from 'rc-resize-observer';
import { useEffect, useRef, useState } from 'react';
interface PreviewUserProps {}

const PreviewUser: React.FC<PreviewUserProps> = ({}) => {
  const [responsive, setResponsive] = useState(false);

  const userRef = useRef<ActionType>();
  const columns: ProColumns<UserData.Account>[] = [
    {
      title: '账号',
      key: 'name',
      dataIndex: 'name',
      width: '80px',
      fixed: 'left',
    },
    {
      title: '激活',
      key: 'isActivation',
      dataIndex: 'isActivation',
      valueType: 'select',
      valueEnum: {
        0: { text: '禁用', status: 'Error' },
        1: { text: '启用', status: 'Success' },
      },
      width: '60px',
    },
    {
      title: '状态',
      key: 'state',
      dataIndex: 'state',
      valueType: 'select',
      valueEnum: {
        0: { text: '禁用', status: 'Error' },
        1: { text: '启用', status: 'Success' },
      },
      width: '60px',
    },
    {
      title: '绑定微信',
      key: 'isWechatUnionid',
      dataIndex: 'isWechatUnionid',
      valueType: 'select',
      valueEnum: {
        0: { text: '否', status: 'Error' },
        1: { text: '是', status: 'Success' },
      },
      width: '60px',
    },
    {
      title: '关注公众号',
      key: 'isWechatWxmpSubscribe',
      dataIndex: 'isWechatWxmpSubscribe',
      valueType: 'select',
      valueEnum: {
        0: { text: '否', status: 'Error' },
        1: { text: '是', status: 'Success' },
      },
      width: '70px',
    },
    {
      title: '电话',
      key: 'phone',
      dataIndex: 'phone',
      width: '120px',
    },
    {
      title: '组织',
      key: 'organizationName',
      dataIndex: 'organizationName',
      width: '180px',
      render: (_, row) => (
        <Space size={[0, 'small']} wrap>
          {row.organizationNames.map((item) => (
            <Tag key={row.id + row.phone + item}>{item}</Tag>
          ))}
        </Space>
      ),
    },
    {
      title: '最后登录时间',
      key: 'loginTime',
      dataIndex: 'loginTime',
      hideInSearch: true,
      width: 150,
    },
  ];

  /**
   * 初始化树形数据(用户数据)
   */
  const [dataTree, setDataTreeState] = useState<DataNode[]>();

  /**
   * 树形列表选择数据
   */
  const [dataTreeSelect, setTreeDataSelectState] = useState<UserData.Organization>();

  useEffect(() => {
    previewTreeOrganizationData();
  }, []);

  /**
   * 本月选题计划
   */
  const previewTreeOrganizationData = async () => {
    try {
      const response = await treeOrganization();
      if (response.code === 0) {
        const treeData = new Array<DataNode>();
        treeData.push({
          title: '融媒通',
          key: '0',
          item: { id: '0', name: '融媒通' },
          children: readyTreeData(response.data),
        });
        setDataTreeState(treeData);
      }
    } catch (error) {}
  };

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(data: Array<UserData.Organization>): any {
    const treeData = new Array();
    if (data) {
      data.forEach((val, idx, array) => {
        treeData.push({
          title: val.name,
          key: val.id,
          type: val.type,
          children: readyTreeData(val.children as Array<UserData.Organization>),
          icon: <FolderOutlined />,
        });
      });
    }
    return treeData;
  }

  /**
   * 根据key加载组织详情
   * @param key
   */
  const loadOrganizationItemData = async (key: string | undefined) => {
    try {
      const response = await previewOrganizationStatistics({ id: key });
      if (response.code === 0) {
        setTreeDataSelectState(response.data);
      }
    } catch (error) {}
  };

  return (
    <RcResizeObserver
      key="resize-observer"
      onResize={(offset) => {
        setResponsive(offset.width < 596);
      }}
    >
      <>
        <ProCard
          title="系统用户"
          // extra={moment().format('LLLL')}
          direction={responsive ? 'column' : 'row'}
          bordered={false}
          headerBordered={false}
        >
          <ProCard
            title={
              <div style={{ display: 'flex' }}>
                <div
                  style={{
                    backgroundImage: 'linear-gradient(98deg,#A9D5FC,#A6CDFB)',
                    padding: 10,
                    width: 300,
                    marginLeft: '-25px',
                    borderRadius: 5,
                  }}
                >
                  <span>组织单位</span>
                </div>
              </div>
            }
            colSpan={responsive ? '100%' : '20%'}
            bordered={false}
            direction={responsive ? 'column' : 'row'}
          >
            {dataTree && dataTree.length ? (
              <Tree
                defaultExpandedKeys={['0']}
                height={637}
                showLine={{ showLeafIcon: false }}
                showIcon={true}
                treeData={dataTree}
                onSelect={(selectedKeys: React.Key[], info: any) => {
                  if (info.node.pos.length == 3 && info.selected) {
                    setTreeDataSelectState({
                      id: '',
                      type: info.node.type,
                      name: info.node.title,
                    } as UserData.Organization);
                  } else if (info.selected) {
                    setTreeDataSelectState({
                      id: info.node.key,
                      type: info.node.type,
                      name: info.node.title,
                    } as UserData.Organization);
                    // loadOrganizationItemData(info.node.key);
                  } else {
                    setTreeDataSelectState({
                      id: '0',
                      name: '融媒通',
                    } as UserData.Organization);
                  }
                  userRef.current?.reset();
                }}
              />
            ) : (
              '暂无数据'
            )}
          </ProCard>
          <ProCard
            // title={`用户信息${dataTreeSelect?.name ? ` - ${dataTreeSelect?.name}` : ''}`}
            split={responsive ? 'horizontal' : 'vertical'}
          >
            <ProTable<AdminAccountData.Account>
              // cardProps={false}
              actionRef={userRef}
              columns={columns}
              request={async (params = {}) => {
                const response = await getAccountPage({
                  ...params,
                  isHide: 0,
                  organizationId: dataTreeSelect?.id,
                  organizationType: dataTreeSelect?.type,
                });

                return Promise.resolve({
                  data: response.data.data,
                  total: response.data.total,
                  success: response.code === 0,
                });
              }}
              rowKey="id"
              dateFormatter="string"
              bordered
              search={{
                filterType: 'light',
              }}
              pagination={{
                showQuickJumper: true,
                showSizeChanger: true,
                defaultPageSize: 10,
              }}
            />
          </ProCard>
        </ProCard>
        <br />
      </>
    </RcResizeObserver>
  );
};

export default PreviewUser;
